import _ from 'lodash'
import { asyncRoutes, constantRoutes, REMOTE_ROUTES } from '@/router'

// 全局配置
const remoteRoutesConfigMap = {}

// 将后台返回的json权限数据格式化（递归遍历子节点）
const remoteRouteMapFunc = (item) => {
  if(Object.keys(remoteRoutesConfigMap).length <= 0) {
    // 尚未初始化全局配置时
    for (const route of REMOTE_ROUTES) {
      remoteRoutesConfigMap[route.path] = route
    }
  }

  const route = {
    meta: {
      title: item.name,
      icon: item.icon,
    },
  }

  item.path = item.path || item.router
  // 组件
  if (item.path in remoteRoutesConfigMap) {
    route.component = remoteRoutesConfigMap[item.path].component
  }

  // 路径
  if (/^\/[^/]+$/.test(item.path)) {
    // 一级菜单
    route.path = item.path
  } else {
    // 其他菜单
    const paths = item.path.split('/')
    route.path = paths[paths.length - 1]
  }

  // 下一级
  if (item.children && item.children.length) {
    route.children = item.children.map(remoteRouteMapFunc)
  }

  return route
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach((route) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  remoteRoutes: [], // 远程路由
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_REMOTE_ROUTES: (state, routes) => {
    state.remoteRoutes = routes.map(remoteRouteMapFunc)
  },
}

const actions = {
  generateRoutes({ commit, state }) {
    return new Promise((resolve) => {
      // let accessedRoutes
      // if (roles.includes('admin')) {
      //   accessedRoutes = asyncRoutes || []
      // } else {
      //   accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      // }
      const accessedRoutes = state.remoteRoutes.concat(asyncRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
